package cn.simon.free.redis.mq.utils;

import com.google.common.base.Splitter;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

/**
 * @author simon
 * @date 2021/7/22 10:38
 * @copyright:
 * @modifier
 * @motto a no talent, people who have to study hard
 */
@Slf4j
public class IpUtils {

    @SneakyThrows
    public static String getLocalIpAddress() {
        Enumeration<NetworkInterface> networkInterfaceEnumeration = NetworkInterface.getNetworkInterfaces();
        try {
            while (networkInterfaceEnumeration.hasMoreElements()) {
                NetworkInterface networkInterface = networkInterfaceEnumeration.nextElement();
                if (networkInterface.isLoopback() || networkInterface.isVirtual() || !networkInterface.isUp()) {
                    // don't something
                } else {
                    Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
                    while (addresses.hasMoreElements()) {
                        InetAddress inetAddress = addresses.nextElement();
                        if (inetAddress instanceof Inet4Address) {
                            return inetAddress.getHostAddress();
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("ip 地址获取失败,原因:", e);
        }
        return "";
    }

    public static void main(String[] args) {
        String localIpAddress = IpUtils.getLocalIpAddress();
        String s = Splitter.on(".").splitToList(localIpAddress).stream().skip(3).findFirst().get();
        log.info("{}", Long.valueOf(s));
    }
}
